package com.spzx.channel.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.spzx.channel.service.IItemService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.*;
import com.spzx.product.api.domain.vo.ItemVo;
import com.spzx.product.api.domain.vo.SkuStockVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class ItemServiceImpl implements IItemService {
    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public ItemVo getItem(Long skuId) {
        //  前端 -> channel (bloomFiler -> openFegin)  -> Product(切面（ redis -> 分布式锁 -> 数据库）)
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("sku:bloom:filter");
        if (! bloomFilter.contains(skuId)){
            log.error("用户查询商品sku不存在:{}"+skuId);
            throw new ServiceException("用户查询商品sku不存在");
        }
        ItemVo itemVo = new ItemVo();
        //1.根据skuId查询ProductSku
        CompletableFuture<ProductSku> skuCompletableFuture = CompletableFuture.supplyAsync(() -> {
            R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (R.FAIL == productSkuResult.getCode()) {
                throw new ServiceException(productSkuResult.getMsg());
            }
            ProductSku productSku = productSkuResult.getData();
            itemVo.setProductSku(productSku);
            return productSku;
        },threadPoolExecutor);


        //2.根据productId查询Product
        CompletableFuture<Void> productCompletableFuture = skuCompletableFuture.thenAcceptAsync((productSku)-> {
            R<Product> productResult = remoteProductService.getProductInfo(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == productResult.getCode()) {
                throw new ServiceException(productResult.getMsg());
            }
            Product product = productResult.getData();
            itemVo.setProduct(product);

            //2.1 查询轮播图
            String sliderUrls = product.getSliderUrls();
            String[] sliderUrlsStringArray = sliderUrls.split(",");
            itemVo.setSliderUrlList(Arrays.asList(sliderUrlsStringArray));

            //2.2 获取商品规格信息
            String specValue = product.getSpecValue();
            JSONArray specValueJsonArray = JSON.parseArray(specValue);
            itemVo.setSpecValueList(specValueJsonArray);
        },threadPoolExecutor);


        //3.根据skuId查询SkuPrice
        CompletableFuture<Void> skuPriceCompletableFuture = CompletableFuture.runAsync(() -> {
            R<SkuPrice> productSkuPriceResult = remoteProductService.getProductSkuPrice(skuId, SecurityConstants.INNER);
            if (R.FAIL == productSkuPriceResult.getCode()) {
                throw new ServiceException(productSkuPriceResult.getMsg());
            }
            SkuPrice skuPrice = productSkuPriceResult.getData();
            itemVo.setSkuPrice(skuPrice);
        }, threadPoolExecutor);


        //4.根据productId查询ProductDetails,可以获取到详情图片列表
        CompletableFuture<Void> productDetailsCompletableFuture = skuCompletableFuture.thenAcceptAsync(productSku -> {
            R<ProductDetails> productDetailsResult = remoteProductService.getProductDetails(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == productDetailsResult.getCode()) {
                throw new ServiceException(productDetailsResult.getMsg());
            }
            ProductDetails productDetails = productDetailsResult.getData();
            String productDetailsImageUrls = productDetails.getImageUrls();
            String[] imageUrlsStringArray = productDetailsImageUrls.split(",");
            itemVo.setDetailsImageUrlList(Arrays.asList(imageUrlsStringArray));
        }, threadPoolExecutor);


        //5.根据skuId查询SkuStockVo
        CompletableFuture<Void> skuStockVoCompletableFuture = CompletableFuture.runAsync(() -> {
            R<SkuStockVo> skuStockResult = remoteProductService.getSkuStock(skuId, SecurityConstants.INNER);
            if (R.FAIL == skuStockResult.getCode()) {
                throw new ServiceException(skuStockResult.getMsg());
            }
            SkuStockVo skuStockVo = skuStockResult.getData();
            itemVo.setSkuStockVo(skuStockVo);
        }, threadPoolExecutor);


        //6. 根据productId查询sku列表的数据，得到Map<String,Long>  规格对应skuId的Map集合
        CompletableFuture<Void> mapCompletableFuture = skuCompletableFuture.thenAcceptAsync((productSku) -> {
            R<Map<String, Long>> skuSpecInfoResult = remoteProductService.getSkuSpecInfo(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == skuSpecInfoResult.getCode()) {
                throw new ServiceException(skuSpecInfoResult.getMsg());
            }
            Map<String, Long> skuSpecValueMap = skuSpecInfoResult.getData();
            itemVo.setSkuSpecValueMap(skuSpecValueMap);
        }, threadPoolExecutor);

        CompletableFuture.allOf(skuCompletableFuture,
                productCompletableFuture,
                skuPriceCompletableFuture,
                productDetailsCompletableFuture,
                skuStockVoCompletableFuture,
                mapCompletableFuture).join();
        return itemVo;
    }


}
